package goLogger

import (
	"fmt"
	"strings"
	"time"
)

//日志结构体
type ConsolLogger struct {
	level LogLevel
}

//Newlog构造函数
func NewConsolLogger(levelStr string) (ConsolLogger, error) {
	level, err := parseLoglevel(levelStr)
	if err != nil {
		panic(err)
	}
	return ConsolLogger{
		level: level,
	}, nil
}

//将传入的未格式化信息格式化，并打印到屏幕
func (c ConsolLogger) log(l LogLevel, message string, a ...interface{}) {
	if c.enable(l) {
		msg := fmt.Sprintf(message, a...)
		now := time.Now()
		funName, fileName, lineNum := GetInfo(3)
		logLevelString, ok := unparseLogLevel(l)
		funName = strings.Split(funName, ".")[1]

		if ok != nil {
			panic("Unparse LogLevel to string Failed!")
		}
		fmt.Printf("[%s] [%s] [%s:%s:%d] %s\n", now.Format("2006-01-02 15:04:05"), logLevelString, fileName, funName, lineNum, msg)
	}

}

func (c ConsolLogger) enable(level LogLevel) bool {
	return level >= c.level
}

//格式化字符串
func (c ConsolLogger) Debug(format string, a ...interface{}) {
	c.log(DEBUG, format, a...)
}

func (c ConsolLogger) Info(format string, a ...interface{}) {
	c.log(INFO, format, a...)
}

func (c ConsolLogger) Warn(format string, a ...interface{}) {
	c.log(WARN, format, a...)
}

func (c ConsolLogger) Error(format string, a ...interface{}) {
	c.log(WARN, format, a...)
}
